package com.example.lxj.base.aspectj;

import com.example.lxj.base.annoation.Permission;
import com.example.lxj.base.exception.AccessFailedException;
import com.example.lxj.base.service.PermissionService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限切面
 */
@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private PermissionService permissionService;

    @Around("@within(org.springframework.web.bind.annotation.RestController) && execution(* *(..)) &&  @annotation(permission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, Permission permission) throws Throwable {
        // 获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String permissionValue = permission.value();
        String[] parts = permissionValue.split(":");
        if (parts.length != 3) {
            throw new RuntimeException("Invalid permission format");
        }
        // 调用权限服务验证当前用户是否有权限
        if (!permissionService.checkPermission( permissionValue, request)) {
            throw new AccessFailedException("权限校验失败");
        }
        return joinPoint.proceed();
    }
}
